<template>
    <div class="register-container">
        <div class="register-card">
            <h3>用户注册</h3>
            <el-form :model="registerForm" ref="registerFormRef" :rules="rules" label-width="80px">
                <!-- 用户名作为账号 -->
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="registerForm.username" placeholder="请设置用户名（作为登录账号）"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="registerForm.password" placeholder="请设置密码（6-20位）"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input type="password" v-model="registerForm.confirmPassword" placeholder="请再次输入密码"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="registerForm.phone" placeholder="请输入手机号（选填）"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleRegister" style="width: 45%">注册</el-button>
                    <el-button @click="handleBack" style="width: 45%; margin-left: 10%">返回登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import request from '@/utils/request';

const router = useRouter();
const registerFormRef = ref();

// 注册表单数据（用户名作为账号）
const registerForm = reactive({
    username: '', // 用户名即账号
    password: '',
    confirmPassword: '',
    phone: '' // 可选填
});

// 表单校验规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 16, message: '用户名长度为3-16位', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: '用户名仅支持中文、字母、数字和下划线', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== registerForm.password) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    phone: [
        {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号格式',
            trigger: 'blur'
        }
    ]
};

// 提交注册
const handleRegister = async () => {
    // 先进行前端表单校验
    try {
        await registerFormRef.value.validate();
    } catch (error) {
        return; // 校验失败则不提交
    }

    // 调用后端注册接口
    try {
        const res = await request.post('/user/register', {
            username: registerForm.username, // 用户名作为账号
            password: registerForm.password,
            phone: registerForm.phone || ''
        });

        if (res.data.success) {
            ElMessage.success('注册成功！即将跳转到登录页');
            setTimeout(() => {
                router.push('/login'); // 注册成功跳登录
            }, 1500);
        } else {
            ElMessage.error(res.data.msg || '注册失败，请重试');
        }
    } catch (error) {
        console.error('注册请求失败：', error);
        ElMessage.error('网络异常，注册失败');
    }
};

// 返回登录页
const handleBack = () => {
    router.push('/login');
};
</script>

<style scoped>
.register-container {
    width: 100vw;
    height: 100vh;
    background-image: url("../assets/5e0014d4b180d33c654579f10be90fc.png");
    background-size: cover;
    background-repeat: no-repeat;
    display: flex;
    justify-content: center;
    align-items: center;
}

.register-card {
    width: 420px;
    padding: 30px;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
}

h3 {
    text-align: center;
    margin-bottom: 25px;
    color: #333;
}
</style>